/*
 * Copyright (C) 2010 The MobileSecurePay Project
 * All right reserved.
 * author: shiqun.shi@alipay.com
 */

package com.sd.activity;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

import com.alex.http.AGetReuqest;
import com.alex.http.AHandledResult;
import com.alex.http.AHttpEngine;
import com.alex.http.AHttpListener;
import com.alex.log.ALog;
import com.alipay.android.appDemo4.AlixId;
import com.alipay.android.appDemo4.BaseHelper;
import com.alipay.android.appDemo4.MobileSecurePayHelper;
import com.alipay.android.appDemo4.MobileSecurePayer;
import com.alipay.android.appDemo4.PartnerConfig;
import com.alipay.android.appDemo4.ProductListAdapter;
import com.alipay.android.appDemo4.Products;
import com.alipay.android.appDemo4.ResultChecker;
import com.alipay.android.appDemo4.Rsa;
import com.sd.activity.r.R;
import com.sd.util.LoadingProgressDialog;
import com.sd.util.RechargeHandleable;
import com.sd.util.StringUtils;
import com.sd.view.ToastManager;
import com.sd.view.ViewUtil;

/**
 * 模拟商户应用的商品列表，交易步骤。
 * 
 * 1. 将商户ID，收款帐号，外部订单号，商品名称，商品介绍，价格，通知地址封装成订单信息 2. 对订单信息进行签名 3.
 * 将订单信息，签名，签名方式封装成请求参数 4. 调用pay方法
 * 
 * @version v4_0413 2012-03-02
 */
public class AlixDemo extends Activity implements 
		OnItemLongClickListener, OnClickListener, AHttpListener {
	static String TAG = "AppDemo4";

	private ImageButton mReturn;
	//
	// 模拟商户商品列表
	ListView mproductListView = null;
	ProductListAdapter m_listViewAdapter = null;
	ArrayList<Products.ProductDetail> mproductlist;
	private Button mCardTypeBT;
	private ProgressDialog mProgress = null;
	String[]strings;
	private Button mRechargeBT;
	private LinearLayout mWarmTipLL;
	//
	// Called when the activity is first created.
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//
		// check to see if the MobileSecurePay is already installed.
		// 检测安全支付服务是否被安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		mspHelper.detectMobile_sp();

		setContentView(R.layout.remote_service_binding);

		mCardTypeBT = (Button)findViewById(R.id.card_type);
		mCardTypeBT.setOnClickListener(this);
		
		mRechargeBT = (Button)findViewById(R.id.recharge);
		mRechargeBT.setOnClickListener(this);
		
		mWarmTipLL = (LinearLayout)findViewById(R.id.warmtipLL);
		mWarmTipLL.addView(ViewUtil.getWarmTips(this, R.string.warmtip0));
		
		mReturn = (ImageButton) findViewById(R.id.return_btn);
		mReturn.setOnClickListener(this);
		
		alixType = 0;
		strings = this.getResources().getStringArray(R.array.alix_type);
		mCardTypeBT.setText(strings[alixType]);
		
	}

	/**
	 * get the selected order info for pay. 获取商品订单信息
	 * 
	 * @param position
	 *            商品在列表中的位置
	 * @return
	 */
	String getOrderInfo() {
		String strOrderInfo = "partner=" + "\"" + PartnerConfig.PARTNER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "seller=" + "\"" + PartnerConfig.SELLER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "out_trade_no=" + "\"" + mOutTradeNo + "\"";
		strOrderInfo += "&";
		strOrderInfo += "subject=" + "\"" + "从客户端充值subject"
				+ "\"";
		strOrderInfo += "&";
		strOrderInfo += "body=" + "\"" + "从客户端充值body" + "\"";
		strOrderInfo += "&";
		strOrderInfo += "total_fee=" + "\""
				+ mCardTypeBT.getText().toString().replace("元", "") + "\"";
		strOrderInfo += "&";
		strOrderInfo += "notify_url=" + "\""
				+ "http://wap.qidian.cn/pay/alipay_notice.do?mtd=alipay_app_notice" + "\"";

		return strOrderInfo;
	}

	/**
	 * get the out_trade_no for an order. 获取外部订单号
	 * 
	 * @return
	 */
	String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String strKey = format.format(date);

		java.util.Random r = new java.util.Random();
		strKey = strKey + r.nextInt();
		strKey = strKey.substring(0, 15);
		return strKey;
	}

	//
	//
	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param signType
	 *            签名方式
	 * @param content
	 *            待签名订单信息
	 * @return
	 */
	String sign(String signType, String content) {
		return Rsa.sign(content, PartnerConfig.RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 * @return
	 */
	String getSignType() {
		String getSignType = "sign_type=" + "\"" + "RSA" + "\"";
		return getSignType;
	}

	/**
	 * get the char set we use. 获取字符集
	 * 
	 * @return
	 */
	String getCharset() {
		String charset = "charset=" + "\"" + "utf-8" + "\"";
		return charset;
	}

	/**
	 * the onItemClick for the list view of the products. 商品列表商品被点击事件
	 */
	public void onItemClick() {
		//
		// check to see if the MobileSecurePay is already installed.
		// 检测安全支付服务是否安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		boolean isMobile_spExist = mspHelper.detectMobile_sp();
		if (!isMobile_spExist)
			return;

		// check some info.
		// 检测配置信息
		if (!checkInfo()) {
			BaseHelper
					.showDialog(
							AlixDemo.this,
							"提示",
							"缺少partner或者seller，请在src/com/alipay/android/appDemo4/PartnerConfig.java中增加。",
							R.drawable.info);
			return;
		}

		// start pay for this order.
		// 根据订单信息开始进行支付
		try {
			// prepare the order info.
			// 准备订单信息
			String orderInfo = getOrderInfo();
			// 这里根据签名方式对订单信息进行签名
			String signType = getSignType();
			String strsign = sign(signType, orderInfo);
			// 对签名进行编码
			strsign = URLEncoder.encode(strsign);
			// 组装好参数
			String info = orderInfo + "&sign=" + "\"" + strsign + "\"" + "&"
					+ getSignType();
			// start the pay.
			// 调用pay方法进行支付
			MobileSecurePayer msp = new MobileSecurePayer();
			boolean bRet = msp.pay(info, mHandler, AlixId.RQF_PAY, this);

			if (bRet) {
				// show the progress bar to indicate that we have started
				// paying.
				// 显示“正在支付”进度条
				closeProgress();
				mProgress = BaseHelper.showProgress(this, null, "正在支付", false,
						true);
			} else
				;
		} catch (Exception ex) {
			Toast.makeText(AlixDemo.this, R.string.remote_call_failed,
					Toast.LENGTH_SHORT).show();
		}
	}

	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		return false;
	}

	/**
	 * check some info.the partner,seller etc. 检测配置信息
	 * partnerid商户id，seller收款帐号不能为空
	 * 
	 * @return
	 */
	private boolean checkInfo() {
		String partner = PartnerConfig.PARTNER;
		String seller = PartnerConfig.SELLER;
		if (partner == null || partner.length() <= 0 || seller == null
				|| seller.length() <= 0)
			return false;

		return true;
	}

	//
	// the handler use to receive the pay result.
	// 这里接收支付结果，支付宝手机端同步通知
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String strRet = (String) msg.obj;

				Log.e(TAG, strRet);// 05-09 17:08:45.280: E/AppDemo4(3358):
									// resultStatus={9000};memo={};result={partner="2088201564809153"&seller="2088201564809153"&out_trade_no="050917083121576"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"&notify_url="http://notify.java.jpxx.org/index.jsp"&success="true"&sign_type="RSA"&sign="d9pdkfy75G997NiPS1yZoYNCmtRbdOP0usZIMmKCCMVqbSG1P44ohvqMYRztrB6ErgEecIiPj9UldV5nSy9CrBVjV54rBGoT6VSUF/ufjJeCSuL510JwaRpHtRPeURS1LXnSrbwtdkDOktXubQKnIMg2W0PreT1mRXDSaeEECzc="}

				switch (msg.what) {
				case AlixId.RQF_PAY: {
					//
					closeProgress();
					
					
					// 从通知中获取参数
					try {
						// 获取交易状态，具体状态代码请参看文档
						String tradeStatus = "resultStatus=";
						int imemoStart = strRet.indexOf("resultStatus=");
						imemoStart += tradeStatus.length();
						int imemoEnd = strRet.indexOf(";memo=");
						tradeStatus = strRet.substring(imemoStart, imemoEnd);
						
						String out_trade_no = "out_trade_no=";
						int outStart = strRet.indexOf("out_trade_no=");
						outStart += out_trade_no.length()+1;
						int outEnd = strRet.indexOf("&subject=")-1;
						out_trade_no = strRet.substring(outStart, outEnd);
						
						
						
						// 对通知进行验签
						ResultChecker resultChecker = new ResultChecker(strRet);

						int retVal = resultChecker.checkSign();
						// 返回验签结果以及交易状态
						// 验签失败
						if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
							ToastManager.getInstance().showText(AlixDemo.this, R.string.msg_recharge_fail);
							/*BaseHelper.showDialog(
									AlixDemo.this,
									"提示",
									getResources().getString(
											R.string.check_sign_failed),
									android.R.drawable.ic_dialog_alert);*/
						} else {
							ToastManager.getInstance().showText(AlixDemo.this, R.string.msg_recharge_succeess);
							// 验签成功
							/*BaseHelper.showDialog(AlixDemo.this, "提示", "状态码:"
									+ tradeStatus, R.drawable.info);*/
						}

					} catch (Exception e) {
						e.printStackTrace();

						BaseHelper.showDialog(AlixDemo.this, "提示", strRet,
								R.drawable.info);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	//
	//
	/**
	 * the OnCancelListener for lephone platform. lephone系统使用到的取消dialog监听
	 */
	public static class AlixOnCancelListener implements
			DialogInterface.OnCancelListener {
		Activity mcontext;

		public AlixOnCancelListener(Activity context) {
			mcontext = context;
		}

		public void onCancel(DialogInterface dialog) {
			mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	}

	//
	// close the progress bar
	// 关闭进度框
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回键监听事件
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			BaseHelper.log(TAG, "onKeyDown back");

			this.finish();
			return true;
		}

		return false;
	}

	//
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.v(TAG, "onDestroy");

		try {
			mProgress.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();

		switch (v_id) {
		case R.id.return_btn:
			finish();
			break;
		case R.id.card_type:
			showDialog(0);
			break;
		case R.id.recharge:
			sendOut();
			
			break;
		default:
			break;
		}
	}

	private int alixType;
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		
		return new AlertDialog.Builder(AlixDemo.this)
        .setTitle(R.string.hint_card_type)
        .setSingleChoiceItems(R.array.alix_type, 0, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	alixType = whichButton;
            }
        })
        .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	mCardTypeBT.setText(strings[alixType]);
                /* User clicked Yes so do some stuff */
            }
        })
        .setNegativeButton(R.string.btn_cancel, null)
       .create();
	}
	
	@Override
	public void onError(long arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		LoadingProgressDialog.dismiss();
		ALog.e("onError");
	}

	@Override
	public void onResult(long arg0, Bundle arg1, AHandledResult arg2) {
		// TODO Auto-generated method stub
		LoadingProgressDialog.dismiss();
		ALog.e("onResult");
		String paramString = (String)arg2.mObj;
		String code = StringUtils.getValueByKey0(paramString, "code");
		String message = StringUtils.getValueByKey0(paramString, "message");
		if(code.equals("0")){
			onItemClick();
			ALog.e("向服务端发送  mOutTradeNo");
		}else{
			ToastManager.getInstance().showText(this, R.string.msg_paying_fail);
		}
	}
	
	private String mOutTradeNo = "";
	private void sendOut(){
		
		LoadingProgressDialog.show(this, R.string.msg_paying);
		mOutTradeNo = getOutTradeNo();
		
		int end = BookStoreActivity.user.indexOf(";;");
		
		String sid = BookStoreActivity.user.substring(0, end);
		ALog.e("sid:"+sid);
		StringBuffer url = new StringBuffer();
		url.append("http://wap.qidian.cn/apps/apppresubmit.do?");
		url.append("prit=");
		url.append("t");
		url.append("&userid=");
		url.append(sid);
		url.append("&out_trade_no=");
		url.append(mOutTradeNo);
		ALog.e(url.toString());
		//HttpUtil.readStringFromUrl(url.toString(), null, 6000, null);
		AGetReuqest getOperation = new AGetReuqest(0, url.toString(), AlixDemo.this,RechargeHandleable.getInstance(),null);
		AHttpEngine.getInstance().request(getOperation);
	}
}